'use client';

import React, { useEffect, useState } from "react";
import { fetchWithToken,myLoader } from '../../utils/api';
import Link from 'next/link';
import SimpleModal from '../../components/SimpleModal';
import Image from 'next/image';


interface JobGpupicId {
  id: string;
  collectionId: string;
  pic: string;
  revisedPrompt: string;
}

interface FavoriteItem {
  id: string;
  created: string;
  expand: {
    job_gpupic_id: JobGpupicId;
  };
}

const Profile = () => {
  const [favorites, setFavorites] = useState<FavoriteItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [recordIdToDelete, setRecordIdToDelete] = useState<string | null>(null);
  

  useEffect(() => {
    const fetchFavorites = async () => {
      try {
        const response = await fetchWithToken('/api/collections/tatoo_history_pic/records?sort=-created&page=1&perPage=30&filter=job_gpupic_id.by_user=\'5h5mfcaf8r8wjoa\'&is_delete=false&expand=job_gpupic_id');
        setFavorites(response.items);
      } catch (err) {
        setError('加载收藏失败');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchFavorites();
  }, []);

  const handleDelete = (recordId: string) => {
    setRecordIdToDelete(recordId);
    setIsModalOpen(true);
  };

  const confirmDelete = async () => {
    try {
      const formData = new FormData();
      formData.append('is_delete', 'true');

      await fetchWithToken(`/api/collections/tatoo_history_pic/records/${recordIdToDelete}`, {
        method: 'PATCH',
        body: formData,
      });
      // setFavorites(favorites.filter(item => item.id !== recordIdToDelete));
      setFavorites(favorites.filter(item => item.id !== String(recordIdToDelete)));

      
   
 
    } catch (err) {
      console.error(err);
      alert('删除失败');
    } finally {
      setIsModalOpen(false);
      setRecordIdToDelete(null);
    }
  };

  if (loading) return <div>加载中...</div>;
  if (error) return <div>{error}</div>;

  return (
    <div className="p-4">
      <Link href="/" className="mb-4 inline-block text-blue-500">返回主页面</Link>
      <h1 className="text-2xl font-bold">我的收藏</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {favorites.map(item => (
          <div key={item.id} className="relative border rounded-lg overflow-hidden shadow-lg transition-transform transform hover:scale-105">
            <Image
                loader={myLoader}
                src={`${item.expand.job_gpupic_id.collectionId}/${item.expand.job_gpupic_id.id}/${item.expand.job_gpupic_id.pic}`}
                alt="收藏的图片"
                width={500}
                height={500}
                className="w-full h-auto"
              />
            <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center text-white opacity-0 hover:opacity-100 transition-opacity">
              <p>{item.expand.job_gpupic_id.revisedPrompt}</p>
              <button onClick={() => handleDelete(item.id)} className="mt-2 bg-red-500 px-2 py-1 rounded">删除</button>
            </div>
            <div className="p-2">
              <p>创建时间: {new Date(item.created).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}</p>
            </div>
          </div>
        ))}
      </div>

      <SimpleModal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="确认删除">
        <p className="text-sm text-gray-500">您确定要删除这条收藏吗？</p>
        <div className="mt-4">
          <button className="bg-red-500 text-white rounded-lg px-4 py-2 mr-2" onClick={confirmDelete}>确认</button>
          <button className="bg-gray-300 text-black rounded-lg px-4 py-2" onClick={() => setIsModalOpen(false)}>取消</button>
        </div>
      </SimpleModal>
    </div>
  );
};

export default Profile; 